﻿
/*
	HTML Plus² Forms		/  	EP LIB		/	Electric Paper 	GmbH 	(ts)
*/

var currentlyActiveInputRef = false; var currentlyActiveInputClassName = false; var bFieldEnter=false; var bFormHasLoaded=false; var curField;var curEPid=""; var curEPoL="";var curImgCtl="";
var oriEFSSubmit="";var EPSTCNT=0;var EPSTix=0;	var EPSTX=0; var EPSTil=-1; var EPSTiT=0; var EPSCnt=0; var EFormCurField=""; var bIsIE6=false;var curEPevent; var pFrmCnt=-1;

function hAI(f) {
	EFormCurField=f.name;
  if (cHLFFld&&f) {
     if (!f.readOnly&&f.type!='checkbox'&&f.type!='radio') {
	     if(currentlyActiveInputRef) currentlyActiveInputRef.className = currentlyActiveInputClassName;
	     currentlyActiveInputClassName = f.className;f.className = 'hlinp-' + f.className;currentlyActiveInputRef = f;       	    
	     if (cHLFFld&&(cHCFld||cHCReq)) {f.style.backgroundColor=cHlBgCol;f.style.borderColor='#ffec00';}
	   }
	}	
	bFieldEnter=true; if (typeof(window.Field_onFocus)!='undefined') Field_onFocus(f);	
}

function bAI(f) {
	EFormCurField=f.name;
  if (cHLFFld&&f) {
     if (!f.readOnly&&f.type!='checkbox'&&f.type!='radio') {  
   	    if (currentlyActiveInputClassName=="") currentlyActiveInputClassName = 'hlinp-' + f.className; 
		if (String(f.className).indexOf(currentlyActiveInputClassName) > -1) f.className = currentlyActiveInputClassName; 			
		if (cHLFFld&&(cHCFld||cHCReq)) f.style.backgroundColor=cFldCol;	      
     }	
  }	
  if (f) {
	EP_HL_REQ_FLD(f); bFieldEnter=false;
	if (typeof(window.Field_onBlur)!='undefined') Field_onBlur(f);
	f.style.borderColor = "#000000";	
  }  
  
}

function getElementsByClass( searchClass, domNode, tagName) { 
	if (domNode == null) domNode = document; if (tagName == null) tagName = '*';
	var el = new Array(); var tags = domNode.getElementsByTagName(tagName); var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) { 
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1) el[j++] = tags[i];
	} 
	return el;
} 

function EP_OKD(f,event) {
	var tp=0;var tor=0;
	if(event.shiftKey && event.keyCode==9) { 
		for (var i=0; i<HtmlFormFields.length; i++) {
			if (HtmlFormFields[i].name==EFormCurField) {tp=HtmlFormFields[i].page;tor=HtmlFormFields[i].taborder; break;}
		}
		for (var i=0; i<HtmlFormFields.length; i++) {
			if (HtmlFormFields[i].taborder==tor-1) { 
				if (HtmlFormFields[i].page!=tp) {EFormSetFocus(EFormGetField(HtmlFormFields[i].name),true);return false;}
				break;
			}
		}			
	};
	if(!event.shiftKey && event.keyCode==9) { 
		for (var i=0; i<HtmlFormFields.length; i++) {
			if (HtmlFormFields[i].name==EFormCurField) {tp=HtmlFormFields[i].page;tor=HtmlFormFields[i].taborder; break;}
		}
		for (var i=0; i<HtmlFormFields.length; i++) {
			if (HtmlFormFields[i].taborder==tor+1) { 
				if (HtmlFormFields[i].page!=tp) {EFormSetFocus(EFormGetField(HtmlFormFields[i].name));	return false;}
				break;
			}
		}
				
	};
}

function EP_HL_REQ_FLD(fx) {
	if (cHCReq) {    
		var f=-1;var curFieldID = "";   
		for (var i = 0; i < HtmlFormFields.length; i++) {
			if (HtmlFormFields[i].name == fx || HtmlFormFields[i].id == fx) {f=i;break;}
			
		}        
	if (f>-1) {
        if (HtmlFormFields[f].required == 1 && HtmlFormFields[f].readonly != 1) {
            curFieldID = HtmlFormFields[f].id;
            switch (HtmlFormFields[f].type) {
            case 'text':
                {
                    if (trim(document.getElementById(curFieldID).value).length == 0) document.getElementById(curFieldID).style.backgroundColor = cReqCol;
                    else document.getElementById(curFieldID).style.backgroundColor = cFldCol;
                    break;
                }

            case 'date':
                {
                    if (trim(document.getElementById(curFieldID).value).length == 0) document.getElementById(curFieldID).style.backgroundColor = cReqCol;
                    else document.getElementById(curFieldID).style.backgroundColor = cFldCol;
                    break;
                }

             case 'select':
                {
                    var ix = 0; var bChk = false;
                    var fx = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                    while (fx) {
                        fx = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                        if (fx) {
                            if (fx.selected && trim(fx.text).length > 0) {							
								if (HtmlFormFields[f].DVIE=='0') {
									if (trim(fx.text)!=trim(HtmlFormFields[f].defval)) bChk=true;
								}
								else bChk = true;								
                                break;
                            }
                        }
                        ix++;
                    }
                    var f = document.HtmlPlusForms[HtmlFormFields[f].name];
                    if (!bChk) f.style.backgroundColor = cReqCol;
                    else f.style.backgroundColor = cFldCol;
                    break;
                }
            case 'checkbox':
                {
                    if (HtmlFormFields[f].subtype == 'sc') {
                        var ix = 0; var bChk = false;
                        var f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                        while (f) {
                            f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                            if (f) {
                                if (f.checked) {
                                    bChk = true; break;
                                }
                            }
                            ix++;
                        }
                        if (!bChk) {
                            var ix = 0; var bChk = false; var f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                            while (f) {
                                var fobj = getElementsByClass(f.className + '_box');
                                if (fobj[0]) fobj[0].style.backgroundColor = cReqCol; 
								ix++; f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                            }
                        } else {
                            var ix = 0; var bChk = false; var f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                            while (f) {
                                var fobj = getElementsByClass(f.className + '_box');
                                if (fobj[0]) fobj[0].style.backgroundColor = cFldCol; 
								ix++; f = document.HtmlPlusForms[HtmlFormFields[f].name][ix];
                            }
                        }
						
                    } else // mc
                    {
                        var fb = String(HtmlFormFields[f].name); fb = fb.substring(0, fb.indexOf(':'));
                        var ix = 0; var bChk = false; var f = document.HtmlPlusForms[fb + ':' + ix];
                        while (f) {
                            f = document.HtmlPlusForms[fb + ':' + ix];
                            if (f) {
                                if (f.checked) {
                                    bChk = true; break;
                                }
                            }
                            ix++;
                        }

                        if (!bChk) {
                            if (strFocus == "") strFocus = String(fb + ':' + '0');
                            var fb = String(HtmlFormFields[f].name);fb = fb.substring(0, fb.indexOf(':'));
                            var ix = 0; var bChk = false;
                            var f = document.HtmlPlusForms[fb + ':' + ix];
                            while (f) {
                                f = document.HtmlPlusForms[fb + ':' + ix];
                                if (f) {
                                    var fobj = getElementsByClass(f.className + '_box'); 
									if (fobj[0]) fobj[0].style.backgroundColor = cReqCol;
                                }
                                ix++;
                            }

                        } else {
                            var fb = String(HtmlFormFields[f].name);
                            fb = fb.substring(0, fb.indexOf(':'));
                            var ix = 0;
                            var bChk = false;
                            var f = document.HtmlPlusForms[fb + ':' + ix];
                            while (f) {
                                f = document.HtmlPlusForms[fb + ':' + ix];
                                if (f) {
                                    var fobj = getElementsByClass(f.className + '_box');
                                    if (fobj[0]) fobj[0].style.backgroundColor = cFldCol;
                                }
                                ix++;
                            }
                        }
                    }
                    break;
                }
            }
        } else {

            if (document.getElementById(HtmlFormFields[f].id)) {
                if (HtmlFormFields[f].type != 'checkbox' && HtmlFormFields[f].readonly == 0) document.getElementById(HtmlFormFields[f].id).style.backgroundColor = cFldCol;
                if (HtmlFormFields[f].type != 'checkbox' && HtmlFormFields[f].readonly == 1) document.getElementById(HtmlFormFields[f].id).style.backgroundColor = 'transparent';
            }

        }
    }
  }  
}

function EP_HL_REQ() {
if (cHCReq && !bIsIE6) {
  var stillreqflds="";var bFormOK=true;var strFocus=""; var curFieldID="";	
  for (var i = 0; i < HtmlFormFields.length; i++) 
  {
      if (HtmlFormFields[i].required==1&&HtmlFormFields[i].readonly!=1) // required field
      {
          curFieldID=HtmlFormFields[i].id;          
      		switch (HtmlFormFields[i].type)
  	        {
		       case 'text':
		       {
	                if (trim(document.getElementById(curFieldID).value).length==0) document.getElementById(curFieldID).style.backgroundColor = cReqCol; else document.getElementById(curFieldID).style.backgroundColor = cFldCol;                
	                break;
		        }

				case 'button':
				{
					if (document.getElementById('img_' + curFieldID)) {
						if (trim(document.getElementById('img_' + curFieldID).src).indexOf('data:image')<0) {								
							document.getElementById('img_' + curFieldID).style.backgroundColor = cReqCol; document.getElementById('fup' + curFieldID).style.backgroundColor = cReqCol; 						
						}
						else {
							document.getElementById('img_' + curFieldID).style.backgroundColor = cFldCol; document.getElementById('fup' + curFieldID).style.backgroundColor = cFldCol; 
						}
					}
					
					break;
				}
				
				
			 case 'signature':
				{
					if (HtmlFormFields[i].ink=='1') {										
						if (parseFloat(HtmlFormFields[i].minFill) > EFormGetPercentFilled('canvas_' + HtmlFormFields[i].id)) {
							HtmlFormFields[i]['obj'].bgColour = cReqCol;
							colSign(i, 'canvas_' + HtmlFormFields[i].id, cReqCol);
						}
						else {
							HtmlFormFields[i]['obj'].bgColour = cFldCol;							
							colSign(i, 'canvas_' + HtmlFormFields[i].id, cFldCol);
						}						
					}					
					break;
				}
				             
	             case 'date':
				{
	                if (trim(document.getElementById(curFieldID).value).length==0) document.getElementById(curFieldID).style.backgroundColor = cReqCol; else document.getElementById(curFieldID).style.backgroundColor = cFldCol;                
	                break;
	             }

	             case 'select':
		       {
                    var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                    while (f)
                    {   
	                     f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
	                     if (f) {
		                      if (f.selected&&trim(f.text).length>0) {
							  
									if (HtmlFormFields[i].DVIE=='0') {
										if (trim(f.text)!=trim(HtmlFormFields[i].defval)) bChk=true;
									}
									else bChk = true;

								break;
							  
							  }		                      
	                     }
	                     ix++;
                    }                    
                    var f = document.HtmlPlusForms[HtmlFormFields[i].name];
                    if (!bChk) f.style.backgroundColor = cReqCol; else f.style.backgroundColor = cFldCol;

                break;
             }             
             case 'checkbox':
             {
                if (HtmlFormFields[i].subtype=='sc')
                {
                    var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                    while (f)
                    {   
	                     f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
	                     if (f) {
		                      if (f.checked) {bChk=true;break;}		                      
	                     }
	                     ix++;
                    }
                    if (!bChk) 
                    {
                      var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                      while (f) {
                         var fobj = getElementsByClass(f.className + '_box');
                         if (fobj[0]) fobj[0].style.backgroundColor = cReqCol;
  	                     ix++; f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                      }
                    }
                    else
                    {
                      var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                      while (f) {
                         var fobj = getElementsByClass(f.className + '_box');
                         if (fobj[0]) fobj[0].style.backgroundColor = cFldCol;
  	                     ix++; f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                      }                    
                    }
                    
                }
                else // mc
                {
                    var fb=String(HtmlFormFields[i].name);fb=fb.substring(0,fb.indexOf(':'));
                    var ix=0;var bChk=false;
                    var f = document.HtmlPlusForms[fb+':'+ix];
                    while (f) {                         
	                     f = document.HtmlPlusForms[fb+':'+ix];
	                     if (f) {
		                      if (f.checked) {bChk=true;break;}		                      
	                     }
	                     ix++;
                    }	                  
                    if (!bChk) 
                    { 
                        bFormOK=false; stillreqflds+=fb+"\n"; if (strFocus=="") strFocus=String(fb+':'+'0');
                        var fb=String(HtmlFormFields[i].name);fb=fb.substring(0,fb.indexOf(':'));
                        var ix=0;var bChk=false;
                        var f = document.HtmlPlusForms[fb+':'+ix];
                        while (f) {                         
    	                     f = document.HtmlPlusForms[fb+':'+ix];
    	                     if (f)
    	                     {
                             var fobj = getElementsByClass(f.className + '_box');
                             if (fobj[0]) fobj[0].style.backgroundColor = cReqCol;                              		                      
    	                     }
    	                     ix++;
                        }	                                           
                    }
                    else
                    {
                        var fb=String(HtmlFormFields[i].name);fb=fb.substring(0,fb.indexOf(':'));
                        var ix=0;var bChk=false;
                        var f = document.HtmlPlusForms[fb+':'+ix];
                        while (f) {                         
    	                     f = document.HtmlPlusForms[fb+':'+ix];
    	                     if (f)
    	                     {
                             var fobj = getElementsByClass(f.className + '_box');
                             if (fobj[0]) fobj[0].style.backgroundColor = cFldCol;                              		                      
    	                     }
    	                     ix++;
                        }	                  
                    }
                }
                break;
             }
          }
    }
    else
    {     
      if (document.getElementById(HtmlFormFields[i].id)) {
	      if (HtmlFormFields[i].type!='checkbox'&&HtmlFormFields[i].readonly==0) document.getElementById(HtmlFormFields[i].id).style.backgroundColor = cFldCol;
	      if (HtmlFormFields[i].type!='checkbox'&&HtmlFormFields[i].readonly==1) document.getElementById(HtmlFormFields[i].id).style.backgroundColor = 'transparent';
      }
    }
  }
 }
}

function jAlert(sC,sT,sE,iT,iC,sEO,iW,iH,bHX)
{	
	//sC: alert html content
	//sT: alert caption
	//sE: js on confirm
	//iT=0 OK only 		sE (if present) is always executed
	//iT=1 OK + Cancel 	confirmation, sE executes only if OK pressed
	//iC=0 Error 		ui-icon-circle-close
	//iC=1 Warning 		ui-icon-notice		default
	//iC=2 Question 	ui-icon-help
	//iC=3 Status 		ui-icon-circle-check 	
	//sEO: js on open
	//bHX: Hide title bars close icon	(default: true)
	
	sC=sC.replace (/\n/g,"<BR/>");
	if (sT==undefined||sT=='') sT=cMsgCapt; if (iC==undefined||iC=='') iC=1;
	var sSpan="<p><span class='ui-icon ";
	if (iC==0) sSpan+="ui-icon-circle-close"; if (iC==1) sSpan+="ui-icon-notice";
	if (iC==2) sSpan+="ui-icon-help"; if (iC==3) sSpan+="ui-icon-circle-check";		
	sSpan+="' style='float:left; margin:0 7px 20px 0;'></span></p>" + sC;
	sSpan=sC;
	
	if (bHX==undefined) bHX=true;
	if (iW==undefined) iW=300;if (iH==undefined) iH=300;
	if (iW) $('#dialog-confirm').dialog( "option", "width",iW);
	if (iH) $('#dialog-confirm').dialog( "option", "height",iH);
	
	$('#dialog-confirm').html(sSpan);
	$('#dialog-confirm').dialog({
		title: sT
	});
	 
	 
	if (sE!=undefined&&sE!='') {
		if (iT==1) {
			$('#dialog-confirm').dialog({
				open: function(event, ui) { if (bHX) $(".ui-dialog-titlebar-close").hide(); if (!bHX) $(".ui-dialog-titlebar-close").show(); if (sEO) eval(sEO); },
				buttons: {
				'OK': function() { eval(sE); $(this).dialog('close'); },				
				Cancel: function() { $(this).dialog('close'); }			
				}
			});
		}
		else {
			$('#dialog-confirm').dialog({
				open: function(event, ui) { if (bHX) $(".ui-dialog-titlebar-close").hide(); if (!bHX) $(".ui-dialog-titlebar-close").show();if (sEO) eval(sEO); },
				buttons: {
				'OK': function() { eval(sE); $(this).dialog('close');}			
				}				
			});		
		}
	}
	else {
		$('#dialog-confirm').dialog({
			open: function(event, ui) { if (bHX) $(".ui-dialog-titlebar-close").hide(); if (!bHX) $(".ui-dialog-titlebar-close").show();if (sEO) eval(sEO); },
			buttons: {
			'OK': function() { $(this).dialog('close'); }
			}		
		});
	}	
	$('#dialog-confirm').dialog('open');
}

function EP_VAL ( field, valstr, valspec ) {	
  var fValue = String(field.value); var vIsNum=fValue.search(/\d/ ); var vIsAlpha=fValue.search(/\D/ ); var bChk=true; var bSpChk=false;  
  if (fValue.length>0) {
	  if (valspec==undefined) valspec=false;
	  curField=field;
		for (var i=0;i<fValue.length;i++) {
			var cX= fValue.charAt(i);if (EP_SPECIAL.indexOf(cX) > -1) { bSpChk=true;break; }        
		}         
	  if (fValue!='') {
		if (valstr=='EP_ALPHA' && valspec==0) {
			if (vIsNum>-1||bSpChk) {bChk=false; 
				jAlert (cMsgAlphaOnly,'','EP_VAL_oA();');
			}        
		}
		if (valstr=='EP_NUMERIC' && valspec==0) {
			if (vIsNum<0||vIsAlpha>-1||bSpChk) {bChk=false; 
			jAlert (cMsgNumOnly,'','EP_VAL_oA();');        
			}        
		}
		if (valstr=='EP_ALPHA + EP_NUMERIC' && valspec==0) {
			if (bSpChk) {bChk=false;         
			jAlert (cMsgNoSpec,'','EP_VAL_oA();');
			}        
		}

		if (valstr=='EP_ALPHA' && valspec==1) {
			if (vIsNum>-1) {bChk=false;         
			jAlert (cMsgAlphaOnly,'','EP_VAL_oA();');
			}        
		}
		if (valstr=='EP_NUMERIC' && valspec==1) {
			if ((vIsNum<0 || isValid(EP_ALPHA,fValue)) ) {bChk=false; 
			jAlert (cMsgNumOnly,'','EP_VAL_oA();');
			}        
		}            
	  }	
	}
	else {bChk=false;field.value = '';} // opera workaround (type number) 
	return bChk;
  //if (!bChk) {field.style.borderColor = "#FF0000"; EFormSetFocus(field); }
}

function EP_VAL_oA() {
	$('#dialog-confirm').dialog('close'); curField.value='';curField.style.borderColor = "#FF0000"; EFormSetFocus(curField);
}

function isValid(p,v) {
  var bRet=false; for (i=0; i<v.length; i++) { var cX= v.charAt(i); if (p.indexOf(cX) > -1) { bRet=true;break; } }
  return bRet;
}

function ep_print() {
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) {  
    for(i=0; i < tabs.length; i++) {
      var obj = document.getElementById(tabs[i]); obj.style.display = "block";obj.style.border = "0px";obj.style.borderStyle = "none";
      obj.style.borderWidth = "0px";obj.style.margin = "0px";obj.style.padding = "0px";          
    }
  }  
  window.print();
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) EFormSetPageFocus(EP_VIEWPAGE);
}

var radioCheck = new Object();
function EPRT($this) {
    if(radioCheck[$this.name] == $this) {
        radioCheck[$this.name] = null; $this.checked = false;
    }
    else radioCheck[$this.name] = $this;
}

function ep_onUnload() {
  if (typeof(window.Form_onClose)!='undefined') Form_onClose();
}

function ep_onLoad() {
	
	if ($.browser.msie && $.browser.version=="6.0") bIsIE6=true;	
	$.support.cors = true;
	
	// check if browser is online with the eforms http-server
	var aURL1 = String(document.location.href + "///").split("/");
	var sURL1 = String(aURL1[0] + "/" + aURL1[1] + "/" + aURL1[2]).toLowerCase();	
	var aURL2 = String(document.getElementById('HPFsubmit').getAttribute("action") + "///").split("/");
	var sURL2 = String(aURL2[0] + "/" + aURL2[1] + "/" + aURL2[2]).toLowerCase();
	if (sURL1==sURL2) EP_BRWAJAX=true;
	if (sURL1.indexOf('http')==0) EP_BRWHTTP=true;	
    if (cLSD) EP_RestoreFromStore();  
    if (EP_PAGEMODE==1||EP_PAGEMODE==2) EFormSetPageFocus(EP_VIEWPAGE);
  
    GetUrlFormFields();EP_AfOnL();
    document.HtmlPlusForms['@BRWSVAR'].value = EP_BRWSVAR;document.HtmlPlusForms['@BRWSVER'].value = EP_BRWSVER;document.HtmlPlusForms['@BRWSPTF'].value = EP_BRWSPTF;  
    
	if (EP_FOCUSFLD!="") {     
		if (cHLFFld) { currentlyActiveInputRef=true;currentlyActiveInputClassName = false; }
		var f = document.HtmlPlusForms[EP_FOCUSFLD];
		if (!f) {
			var fb=String(EP_FOCUSFLD);fb=fb.substring(0,fb.indexOf(':'));
			f = document.HtmlPlusForms[fb+':'+'0'];
		}          
		if (f) {
			var ftype=String(f.type).toLowerCase();
			if (ftype=='radio'||ftype=='undefined') f[0].focus(); else f.focus();
		} 
	}
  
  var inputs = document.getElementsByTagName('input'); // radio toggle
  for(var i=0; i<inputs.length; i++) {
	if(inputs[i].checked) radioCheck[inputs[i].name] = inputs[i];
	if(inputs[i].type=="button") inputs[i].style.display = "block";
  }  
  inputs = document.getElementsByTagName('button');
  for(i=0; i<inputs.length; i++) {
	if(inputs[i].type=="button") inputs[i].style.display = "block";
  }  

  epelall(); fDirty=false;
  if (typeof(window.Form_onLoad)!='undefined') Form_onLoad();

  oriEFSSubmit = $('#EFS__HttpSubmit').html();
  UptEFCNT(); window.scrollTo(0,1);
  bFormHasLoaded=true;
} 

function UptEFCNT() {
  EPSTCNT=EP_StoreCount();
  if (EPSTCNT>0) $('#EFS__HttpSubmit').html(oriEFSSubmit + ' <small>(' + EPSTCNT + ')</small>');
  else $('#EFS__HttpSubmit').html(oriEFSSubmit);
  
}

function EP_submit() {
  var bsOK=true;EP_HL_REQ();  
  if (ep_validate_before_submit()) {
	if (typeof(window.Form_onSubmit)!='undefined') bsOK=Form_onSubmit();       
  	if (bsOK) {   
	  if (EP_DC_Ask) { 	  
  		jAlert (cMsgSendDataAsk,'',"EP_submit_oA();",1,2);	
	}
	else {EP_submit_oA();}       
	}    
  }  
}

function preSubSign() {	
	for (var i = 0; i < HtmlFormFields.length; i++) {
     if (HtmlFormFields[i].type=='signature') { 
		if (HtmlFormFields[i].ink=='1') {
			var cPF=0;cPF=EFormGetPercentFilled('canvas_' + HtmlFormFields[i].id);
			EFormSetValue('PCX_' + HtmlFormFields[i].name, HtmlFormFields[i]['obj'].getSignatureImage('image/jpeg'));								
			if (cPF >= parseFloat(HtmlFormFields[i].minFill)) {
				EFormSetValue(HtmlFormFields[i].name, String(Math.ceil(cPF)));			
			} else EFormSetValue(HtmlFormFields[i].name, '');
		}
	 }
   }
}

function initSign() {
	for (var i = 0; i < HtmlFormFields.length; i++) {
     if (HtmlFormFields[i].type=='signature') { 
		if (HtmlFormFields[i].ink=='1') {
			EPcpys('div_sign_' + HtmlFormFields[i].id,'canvas_' + HtmlFormFields[i].id); HtmlFormFields[i]['obj'] = $('.div_sign_' + HtmlFormFields[i].id).signaturePad({ defaultAction : 'drawIt', drawOnly : true, lineColour: 'transparent', penColour: '#000000', bgColour: cFldCol, output: '#CVS_' + HtmlFormFields[i].id, canvas: '#canvas_' + HtmlFormFields[i].id });
		}
	 }
  }
}

function EP_submit_oA() {	
	preSubSign();covUI(true);var ix=0;	
	$('#dialog-confirm').dialog('close');		
	EFormSetValue('@LOOKUP',""); 
	
	if (EP_PKENCRYPT==1) {
		var datastr=encodeData();			
		EP_resetE();
		document.HtmlPlusForms["@FORMDATA"].value = datastr;
	}

	fDirty=false;

	if (navigator.onLine) {	
		if (EP_DC_METHOD==1 && EP_BRWAJAX) {
			document.HtmlPlusForms["@AJAX"].value = "1";				
			$.ajax({ url: document.getElementById('HPFsubmit').getAttribute("action"), type: "POST", data: $("#HPFsubmit").serialize(), 
				success: function(data) {									
						if (data.indexOf("<!-- DATASUCCESS -->")>=0) {
							EPSTix=parseInt(EPSTCNT);EPSTX=parseInt(EPSTCNT);
							if (EP_DC_Reset) {EP_resetE();EP_SaveForLater(false);}						
							covUI(false); 
							if (document.HtmlPlusForms['@RESPONSEURL'].value != '') {
								window.location.replace(document.HtmlPlusForms['@RESPONSEURL'].value);
							}
							else {
								jAlert(cMsgHttpSend); 
							}

						}
						else {
							bFormHasLoaded=false;EP_SaveToStore(); 							
							if (EP_DC_Reset) {
								EP_resetE();EP_SaveForLater(false); 
							}
							epelall();fDirty=false; covUI(false);	bFormHasLoaded=true;					
						}						
					},			
				statusCode: {
					404: function() {
							jAlert('page not found');
						}		
				},		
				error:  
					function(jqXHR, textStatus, errorThrown) {
						// Handle any errors											
						bFormHasLoaded=false;EP_SaveToStore(); 							
						if (EP_DC_Reset) {
							EP_resetE();EP_SaveForLater(false); 
						}
						epelall(); fDirty=false;covUI(false);	bFormHasLoaded=true;										
						//alert(jqXHR.status);
						//alert(textStatus);
						//alert(errorThrown);
					},
					complete: function() {
				}				
				});
		}
		else {
			document.HtmlPlusForms["@AJAX"].value = "0";	
			document.HtmlPlusForms.submit();
			covUI(false);
			// asynchroner prozess reset nicht sinnvoll	
		}		
	}
	else {
		bFormHasLoaded=false;EP_SaveToStore(); 							
		if (EP_DC_Reset) {
			EP_resetE();EP_SaveForLater(false); 
		}
		epelall();fDirty=false; covUI(false);	bFormHasLoaded=true;					
	}

	
}


function EP_sync() {	
	if (navigator.onLine) {			
		covUI(true);
		EPSTix=parseInt(EPSTCNT);EPSTX=parseInt(EPSTCNT);
		EPSTiT=EPSTix;EPSCnt=0;
		EPSTil=-1;EP_processStore(true);					
	} else alert(cMsgSyncOff);
	
}

function EP_processStore(bNoFWD) {	
		$("#progressbar").show();	
		$("#progressbar").progressbar("value", parseInt(100 * (parseInt(EPSTX)-EPSTix) / EPSTX));			
		if (EPSTix>0) {  
			$('#EFS__HttpSubmit').html(oriEFSSubmit + ' <small>(' + EPSTix + ')</small>');
		}  
		else $('#EFS__HttpSubmit').html(oriEFSSubmit);		
				
	  if (EPSTix>0&&EPSTX>0&&EPSTiT>0) {	      			
		EPSTiT--;EPSTil=GetSynSlt(EPSTil+1);		
		var sFrmDta=GetCnvStoreData(EPSTil);
		// only submit when all required fields are filled
		if (!jQuery.isEmptyObject(sFrmDta)) {	
			$.ajax({ url: document.getElementById('HPFsubmit').getAttribute("action"), type: "POST", data: sFrmDta, 
				success: function(data) {							
					if (data.indexOf("<!-- DATASUCCESS -->")>=0) {								
						RemoveDataStore(EPSTil);EPSTix--;EPSCnt++;
						if (EPSTix>=0) EP_processStore(bNoFWD); 					
					}
					else {
						covUI(false);$("#progressbar").hide('slow');
					}								
				},			
				statusCode: {
					404: function() {
							jAlert('page not found');
						}		
				},		
				error:  
					function(jqXHR, textStatus, errorThrown) {
						// Handle any errors				
						//alert(jqXHR.status);
						//alert(textStatus);
						//alert(errorThrown);												
						covUI(false);$("#progressbar").hide('slow');					
					},
				complete: function()
				{ 
				}				
			});						
		} else if (EPSTiT>=0) EP_processStore(bNoFWD); 
		
	}
	else {
		if (EPSTX>0 || !bNoFWD) {
			if (document.HtmlPlusForms['@RESPONSEURL'].value != '' && !bNoFWD) {
				window.location.replace(document.HtmlPlusForms['@RESPONSEURL'].value);
			}
			else {		
				covUI(false); if (EPSCnt>0) jAlert(cMsgHttpSend); 
			}						
		}
		covUI(false);
		$("#progressbar").hide('slow');		
	}
}

function RemoveDataStore(iP,bS) {
	try {
		var storage = window.localStorage;
	}
	catch (e) {		
		alert(cMsgNaReader);
	}  	
			
	storage.removeItem("F" + iP + "_" + EP_DC_FormID + "@@DSFLAG"); // deleted
	for (var i=0;i<HtmlFormFields.length;i++) {
		try	{					
			storage.removeItem("F" + iP + "_" + EP_DC_FormID + "_" + HtmlFormFields[i].name);
		}
		catch (e) {
		}				
	}
	
	if (bS==undefined) {
		EPSTCNT=parseInt(EPSTCNT)-1;	
		storage.setItem("F_CNT" + EP_DC_FormID, EPSTCNT);
	}	
	
	// pointer eines gelöschten Vorgangs zurücksetzen
	if (iP==pFrmCnt) {	
		if (bS==undefined) {pFrmCnt=-1; EP_resetE();EP_SaveForLater(false); epelall(); fDirty=false;}
	}
	
}

function GetCnvStoreData(iP) {
	var sData = {};
	try {
		var storage = window.localStorage;
	}
	catch (e) {
	}  	
	
	var bReq=false;
	sData["@STORE"] = "1"; // var1
	for (var i = 0; i < HtmlFormFields.length; i++) {
		try {					
			var fdata = "";
			fdata = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "_" + HtmlFormFields[i].name));			
			if (fdata==null||fdata=='null') fdata="";			
			if (HtmlFormFields[i]['required'] != 1) bReq=false; else bReq=true;			
			if (HtmlFormFields[i].type!='checkbox'||HtmlFormFields[i].subtype!='mc') {			
				sData[HtmlFormFields[i].name] = fdata;
				if (bReq&&trim(fdata)=="") { sData={}; break; } // alert('not filled ' + HtmlFormFields[i].name); 
			}
			else {
				// mc behandeln
				var ix=0;var fb=String(HtmlFormFields[i].name);fb=fb.substring(0,fb.indexOf(':')); fdata+="\t";
				var f = document.HtmlPlusForms[fb+':'+ix]; var bMCf=false;
				while (f) {                         
				   f=document.HtmlPlusForms[fb+':'+ix];				   				   
				   if (f) {
					if (fdata.indexOf(String(f.value + "\t"))>=0) {sData[String(fb+':'+ix)] = f.value; bMCf=true; } // kommt MC option in localstorage Eintrag vor?
				   }
				   ix++;
				}
				if (bReq&&!bMCf) { sData={}; break; } // alert('not filled ' + HtmlFormFields[i].name); 
			}			
		}
		catch (e) {
		}				
	}
	return sData;	
}

function GetUrlFormFields() {
  var strReturn = "";var fid=-1;
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ) {
    var strQueryString = strHref.substr(strHref.indexOf("?")+1);var aQueryString = strQueryString.split("&");	
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
        if ( aQueryString[iParam].indexOf("=") > -1 ) {
          var aParam = aQueryString[iParam].split("=");
          aParam[0]=unescape(aParam[0]);aParam[1]=unescape(aParam[1]);EFormSetValue(aParam[0],aParam[1]);
       }
    }
  }
  return unescape(strReturn);
}

function GetFormFieldIDByName(sN) {
  var ix=""; for (var i = 0; i < HtmlFormFields.length; i++) {
     if (HtmlFormFields[i].name==sN) { ix=HtmlFormFields[i].id;break;}
  }
  if (ix=="") {sN+=':0';for (var i = 0; i < HtmlFormFields.length; i++) {
     if (HtmlFormFields[i].name==sN) { ix=HtmlFormFields[i].id;break;} 
	 }
  }    
  return ix;
}

function GetFormFieldIndexByID(sN) {
  var ix=-1; for (var i = 0; i < HtmlFormFields.length; i++) {
     if (HtmlFormFields[i].id==sN) { ix=i;break;}
  }
  return ix;
}

function EP_reset() {
  var bOK=true; if (typeof(window.Form_onReset)!='undefined') bOK=Form_onReset();
	if (bOK) {	
		jAlert (cMsgResetForm,'',"bFormHasLoaded=false;EP_resetE();EP_SaveForLater(false); epelall(); fDirty=false; if (typeof(window.Form_afterReset)!='undefined') Form_afterReset();bFormHasLoaded=true;",1,2);	
  }  
}

function EP_resetE() {
	document.HtmlPlusForms.reset(); pFrmCnt=-1;
	for (var i = 0; i < HtmlFormFields.length; i++) {
	 try {
		if (HtmlFormFields[i].type=='signature') { if (HtmlFormFields[i].ink=='1') { HtmlFormFields[i]['obj'].clearCanvas(); EFormSetValue(HtmlFormFields[i].name, ''); } }
	 } catch (e) { }
	 if (HtmlFormFields[i].type=='button') 
		if (document.getElementById('img_' + HtmlFormFields[i].id)) {
			document.getElementById('img_' + HtmlFormFields[i].id).src=EP0IMG + "/pix.gif";
			document.getElementById('PCX_' + HtmlFormFields[i].id).value="";
		  }
	}
    var inputs = document.getElementsByTagName('input'); // radio toggle
    for(var i=0; i<inputs.length; i++) if(inputs[i].checked) radioCheck[inputs[i].name] = inputs[i];
}

function ep_validate_before_submit() {	
  var stillreqflds="";var bFormOK=true;var strFocus=""; var curFieldID="";var bPass=false;	
  for (var i = 0; i < HtmlFormFields.length; i++) {  
      bPass=false;	
      if (HtmlFormFields[i].pl != undefined) {
        if (HtmlFormFields[i].name!=HtmlFormFields[i].pl) bPass=true;                      
      }
      if (HtmlFormFields[i].required==1 && !bPass) {  // required field
          curFieldID=HtmlFormFields[i].id;
      		switch (HtmlFormFields[i].type)
		      {
			 
			 case 'text':
			   {
                if (document.getElementById(curFieldID).value.length==0) {bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title+"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name;}                
                break;
             }
             
             case 'date':
			   {
                if (document.getElementById(curFieldID).value.length==0) {bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title+"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name;}                
                break;
             }

			 case 'button':
			 {
				if (document.getElementById('img_' + curFieldID)) {				
					if (trim(document.getElementById('img_' + curFieldID).src).indexOf('data:image')<0) {					
						bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title+"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name;						
						EFormSetValue(HtmlFormFields[i].name, "");
					}
					else EFormSetValue(HtmlFormFields[i].name, String(HtmlFormFields[i].minFill));
				}
			 
                break;			 
			 }
			 
			 case 'signature':
				{
					if (HtmlFormFields[i].ink=='1') {										
						if (parseFloat(HtmlFormFields[i].minFill) > EFormGetPercentFilled('canvas_' + HtmlFormFields[i].id)) {
							bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title+"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name;						
						}
					}
					
					break;
				}
				
             case 'select':
             {
                    var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                    while (f) {   
	                     f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
	                     if (f) {
		                      if (f.selected && trim(f.text) !="") {							
								if (HtmlFormFields[i].DVIE=='0') {
									if (trim(f.text)!=trim(HtmlFormFields[i].defval)) bChk=true;
								}
								else bChk = true;								
								
								break;}		                     
	                     }
	                     ix++;
                    }                    
                    if (!bChk) { bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title+"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name; }
              break;
             }
                                       
             case 'checkbox':
             {
                if (HtmlFormFields[i].subtype=='sc') {
                    var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
                    while (f) {   
	                     f = document.HtmlPlusForms[HtmlFormFields[i].name][ix];
	                     if (f) {
		                      if (f.checked) {bChk=true;break;}		                      
	                     }
	                     ix++;
                    }
                    if (!bChk) { bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title + "\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=HtmlFormFields[i].name; }                    
                }
                else  { 
                    var fb=String(HtmlFormFields[i].name);fb=fb.substring(0,fb.indexOf(':'));
                    var ix=0;var bChk=false; var f = document.HtmlPlusForms[fb+':'+ix];
                    while (f) {                         
	                     f = document.HtmlPlusForms[fb+':'+ix];
	                     if (f) {
		                      if (f.checked) {bChk=true;break;}		                      
	                     }
	                     ix++;
                    }
                    if (!bChk) { bFormOK=false; stillreqflds+='&#9679; ' + HtmlFormFields[i].title +"\n"; if (strFocus==""&&HtmlFormFields[i].readonly!=1) strFocus=String(fb+':'+'0'); }
                }
                break;
             }
          }
       }
	}
	
	if (stillreqflds!="") {
		var sdlg=cMsgReqFlds.replace ("%stillreqflds%",stillreqflds);
			curField=EFormGetField(strFocus);
      		jAlert (cMsgReqFlds.replace ("%stillreqflds%",stillreqflds),'', 'ep_validate_before_submit_oA();');
	}
  
  var sFormSubject = GetDynSubject(EP_DC_HEADER);	document.HtmlPlusForms["@FORMHEADER"].value = sFormSubject;  
  return bFormOK;
}

function ep_validate_before_submit_oA() {
	$('#dialog-confirm').dialog('close'); EFormSetFocus(curField);
}

function GetDynSubject(sLine) {
	var EvalArr = String(sLine).split("%");var sNewLine = "";var bField = false;
	for (var ix = 0; ix<EvalArr.length; ix++) {
		if (bField) {
			if (EFormGetField(EvalArr[ix])) sNewLine+=EFormGetValue(EvalArr[ix]);bField=false;
		}
		else {
			sNewLine+=EvalArr[ix];bField=true;
		}
	}
	return sNewLine;
}

function EP_CDR(f, sF, sT, dF) {
var tD=EP_DATE(f,dF,1); // aktuelles Datum als Value
if (!isNaN(tD)) {          
  var sD=new Date(parseInt(sF.substring(0,4)), parseInt(sF.substring(5,7))-1, parseInt(sF.substring(8,10)));  
  var eD=new Date(parseInt(sT.substring(0,4)), parseInt(sT.substring(5,7))-1, parseInt(sT.substring(8,10)));    
  if (tD < sD || tD > eD) {
   		var tempstr = cMsgInvDateRange.replace ("%sad%",sF);tempstr = tempstr.replace ("%ead%",sT); curField=f;
		  jAlert ("[" + f.name + "]\n\n" + tempstr,'','EP_CDR_oA();');	      	  
	}  
  }
}

function EP_CDR_oA() {
	$('#dialog-confirm').dialog('close'); curField.style.borderColor = "#FF0000"; EFormSetFocus(curField);
}

function EP_DATE (fx,x,cM) {
 var bChk=true;var f="";var xt=x; var cS="";
 if (!fx) bChk=false; 
 else  {
   while (1) {       
      f=fx.value.toString(); if (f=="") break;	  
      if (x.indexOf('.')>=0) {cS=".";f=f.split(cS);} 
      else if (x.indexOf('-')>=0) {cS="-";f=f.split(cS);}
      else if (x.indexOf('/')>=0) {cS="/";f=f.split(cS);}        
	  	  
      if (f.length!=3) {bChk=false;break;}      
      xt=ReplaceString(xt,'.',''); xt=ReplaceString(xt,'-',''); xt=ReplaceString(xt,'/','');      
      // dd mm yyyy or yy
      if (xt=="ddmmyyyy"||xt=="ddmmyy")
      {
        f[0]=parseInt(f[0],10);f[1]=parseInt(f[1],10)-1;
		if (f[2].length==2) f[2]=parseInt('2000') + parseInt(f[2],10);		
        var kd=new Date(f[2],f[1],f[0]);
        if (kd.getDate()==f[0] && kd.getMonth()==f[1] && kd.getFullYear()==f[2]) bChk=true; else bChk=false;
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=rightstr("0" + kd.getDate(),2)+cS+rightstr("0" + (kd.getMonth()+1),2)+cS+kd.getFullYear(); }
        else if (xt.indexOf('yy')>=0 && bChk) { fx.value=rightstr("0" + kd.getDate(),2)+cS+rightstr("0" + (kd.getMonth()+1),2)+cS+rightstr("0" + kd.getYear(),2); }        
      }
      
      // mm dd yyyy or yy
      if (xt=="mmddyyyy"||xt=="mmddyy")
      {
        f[0]=parseInt(f[0],10)-1;f[1]=parseInt(f[1],10);		
        if (f[2].length==2) f[2]=parseInt('2000') + parseInt(f[2],10);			
		var kd=new Date(f[2],f[0],f[1]);		
		if (kd.getMonth()==f[0] && kd.getDate()==f[1] && kd.getFullYear()==f[2]) bChk=true; else bChk=false;    				
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=(kd.getMonth()+1) + cS + kd.getDate() + cS + kd.getFullYear(); }
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=rightstr("0" + (kd.getMonth()+1),2)+cS+rightstr("0" + kd.getDate(),2)+cS+kd.getFullYear(); }
        else if (xt.indexOf('yy')>=0 && bChk) { fx.value=rightstr("0" + (kd.getMonth()+1),2)+cS+rightstr("0" + kd.getDate(),2)+cS+rightstr("0" + kd.getYear(),2); }
      }
	  
      // yyyy mm dd or yy
      if (xt=="yyyymmdd"||xt=="yymmdd")
      {
        f[1]=parseInt(f[1],10)-1;f[2]=parseInt(f[2],10);
        if (f[0].length==2) f[0]="20"+f[0];
        var kd=new Date(f[0],f[1],f[2]);
        if (kd.getMonth()==f[1] && kd.getDate()==f[2] && kd.getFullYear()==f[0]) bChk=true; else bChk=false;
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=kd.getFullYear() + cS + (kd.getMonth()+1) + cS + kd.getDate(); }            
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=kd.getFullYear() + cS + rightstr("0" + (kd.getMonth()+1),2)+cS+rightstr("0" + kd.getDate(),2); }
        else if (xt.indexOf('yy')>=0 && bChk) { fx.value=rightstr("0" + kd.getYear(),2) + cS + rightstr("0" + (kd.getMonth()+1),2)+cS+rightstr("0" + kd.getDate(),2); }
      }     
      
      // yyyy dd mm or yy
      if (xt=="yyyyddmm"||xt=="yyddmm")
      {
        f[1]=parseInt(f[1],10);f[2]=parseInt(f[2],10)-1;
        if (f[0].length==2) f[0]="20"+f[0];
        var kd=new Date(f[0],f[2],f[1]);
        if (kd.getMonth()==f[2] && kd.getDate()==f[1] && kd.getFullYear()==f[0]) bChk=true; else bChk=false;    
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=kd.getFullYear() + cS + kd.getDate() + cS + (kd.getMonth()+1); }
        if (xt.indexOf('yyyy')>=0 && bChk) { fx.value=kd.getFullYear() + cS + rightstr("0" + kd.getDate(),2) + cS + rightstr("0" + (kd.getMonth()+1),2); }
        else if (xt.indexOf('yy')>=0 && bChk) { fx.value=rightstr("0" + kd.getYear(),2) + cS +rightstr("0" + kd.getDate(),2) + cS + rightstr("0" + (kd.getMonth()+1),2); }
      }           
      break;
   }
}
 if (!bChk&&cM!=1) {curField=fx;jAlert (cMsgInvDate + " [" + x + "]",'','EP_DATE_oA();'); }
 return kd;
}


function EP_DATE_oA() {
	$('#dialog-confirm').dialog('close'); curField.style.borderColor = "#FF0000"; EFormSetFocus(curField);	
}

function ep_cfld(sN) {
// OK!
  var f=document.HtmlPlusForms[sN]; fid=GetFormFieldIndexByID(sN);
  if (fid<0) fid=GetFormFieldIndexByID(String(sN+':0'));          
  if (fid>-1) {                    
    if (HtmlFormFields[fid].type!='checkbox') f.value='';
    else {   // sc, mc felder
        if (HtmlFormFields[fid].subtype=='sc') {
            var ix=0;var bChk=false;var f = document.HtmlPlusForms[HtmlFormFields[fid].name][ix];
            while (f) {   
               f=document.HtmlPlusForms[HtmlFormFields[fid].name][ix];
               if (f) f.checked=false;           
               ix++;
            }                
        }
        else {
            var ix=0;var fb=String(HtmlFormFields[fid].name);fb=fb.substring(0,fb.indexOf(':'));var f = document.HtmlPlusForms[fb+':'+ix];
            while (f) {                         
               f = document.HtmlPlusForms[fb+':'+ix];
               if (f) f.checked=false;
               ix++;
            }                    
        }                
    }
 }                   
}

function EP_CF(f,c) {
  if (c == 1) f.value = f.value.toString().toUpperCase();
  else if (c == 2) f.value = f.value.toString().toLowerCase();
}

function validate_required(field,alerttxt) {
	with (field) {
		if (value==null||value=="") {jAlert(alerttxt);return false}
		else {return true}
	}
}

function gotoN(sG) {
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) {
      if (EP_VIEWPAGE<EP_PAGECNT) {EFormSetPageFocus(EP_VIEWPAGE+1);} 
  }
  else {
    if (window.pageYOffset!=undefined) window.scrollTo(0,window.pageYOffset+sG); else window.scrollBy(0,sG);
  }
}
function gotoP(sG) {
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) {
      if (EP_VIEWPAGE>1) {EFormSetPageFocus(EP_VIEWPAGE-1);} 
  }
  else { 
    if (window.pageYOffset!=undefined) window.scrollTo(0,window.pageYOffset+sG); else window.scrollBy(0,sG);
  }
}
function gotoF() {
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) {
      EFormSetPageFocus(1); 
  }
  else { 
    window.scrollTo(0,0);
  } 
}

function gotoL() {
  if (EP_PAGEMODE==1||EP_PAGEMODE==2) {
      EFormSetPageFocus(EP_PAGECNT); 
  }
  else {  
    window.scrollTo(0,10000000);
  } 
}

function NavState() {
 if (navigator.onLine == true) jAlert ("Online"); else jAlert("Offline"); 
}

function NavSource() {
 if (window.location.protocol=="file:") jAlert("Lokal");
 if (window.location.protocol=="http:") jAlert("Extern");
}

function EP_zoomin() {
	if(window.parent.document.body.style.zoom!=0) window.parent.document.body.style.zoom*=1.1; else window.parent.document.body.style.zoom=1.2;
}

function EP_zoomout() {
	if(window.parent.document.body.style.zoom!=0) window.parent.document.body.style.zoom*=0.9; else window.parent.document.body.style.zoom=0.8;
}

function EP_zoom100() {
	window.parent.document.body.style.zoom=1;
}

function EP_HELP(fH) {
	if (fH==undefined) fH=EP_DC_mHELP;
	switch (fH) {
		case 1:	{ jAlert (EP_DC_HELP);	break;}
		case 2: {
			if (EP_DC_HELPURL!="") window.open(EP_DC_HELPURL,"","location=1,scrollbars=1,resizable=1,status=1,toolbar=1");
		}
	}
}

function EP_CNR (e,min,max) {
	var dummy = String(e.value).replace(",",".");var tempstr = "";
	if (dummy!="") {
		var fldval = Number (dummy);
		if (fldval<min||fldval>max)	{
			  tempstr = cMsgInvRange.replace ("%min%",min);tempstr = tempstr.replace ("%max%",max)
			  if (EP_DC_ValNum!=0) { curField=e; jAlert("[" + e.name + "]\n\n" + tempstr, '', 'EP_CNR_oA();');
        }
        else e.style.borderColor = "#000000";			  
		}
	}
}

function EP_CNR_oA() {
	$('#dialog-confirm').dialog('close');curField.value='';curField.style.borderColor = "#FF0000"; EFormSetFocus(curField);
}

function noe (field, event) {
	
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++) if (field==field.form.elements[i]) break;
		i = (i + 1) % field.form.elements.length; field.form.elements[i].focus();
		return false;
	}
	else return true;
	
}

function maxl(field,maxlimit) {
	
	if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);
}

var ns6=document.getElementById&&!document.all
function restrictinput(maxlength,e,placeholder) {
	if (window.event&&event.srcElement.value.length>=maxlength)
	return false
	else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
	var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
	if (pressedkey.test(String.fromCharCode(e.which)))
	e.stopPropagation()
	}
}

function countlimit(maxlength,e,placeholder) {
	var theform=eval(placeholder)
	var lengthleft=maxlength-theform.value.length
	var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
	if (window.event||e.target&&e.target==eval(placeholder)){
	if (lengthleft<0)
	theform.value=theform.value.substring(0,maxlength)
	placeholderobj.innerHTML=lengthleft
	}
}

function displaylimit(thename, theid, thelimit) {
	var theform=theid!=""? document.getElementById(theid) : thename
	var limit_text='<b><span id="'+theform.toString()+'">'+thelimit+'</span></b> characters remaining on your input limit'
	if (document.all||ns6)
	document.write(limit_text)
	if (document.all){
	eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
	eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
	}
	else if (ns6){
	document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true);
	document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true);
	}
}

function HtmlSetFocus(f) {
  EFormSetFocus(f);
}

function trim(str) {
  var s="";s=String(str).replace(/^(\s)*/, '');s=s.replace(/(\s)*$/, '');return s;
}

function ltrim(str) {
	return String(str).replace(/^\s+/,"");
}
function rtrim(str) {
	return String(str).replace(/\s+$/,"");
}

function ReplaceString ( String1, suchString, ErsetzString ) {
	while (String1.indexOf(suchString) > -1) String1=String1.replace(suchString,ErsetzString);	return String1;
}

function leftstr(str, n) {
	if (n <= 0) return "";
	else if (n > String(str).length) return str;
	else return String(str).substring(0,n);
}

function rightstr(str, n){
    if (n <= 0) return "";
    else if (n > String(str).length) return str;
    else {var iLen = String(str).length;return String(str).substring(iLen, iLen - n);}
}

function EPPG(f) {   
  var fid=GetFormFieldIndexByID(f.id); var fDst = document.HtmlPlusForms[HtmlFormFields[fid].pl] 
  for (var i = 0; i < HtmlFormFields.length; i++) {      
      if (HtmlFormFields[i].pl==fDst.name) {
        EFormSetValue(HtmlFormFields[i].name,f.value);
      }
  }
}

function EP_SetStoreCnt(ndata) {
	if (EP_BRWHTTP) {
		try {
			var storage = window.localStorage;
			if (!isNaN(ndata)) storage.setItem("F_CNT" + EP_DC_FormID, ndata);
		}
		catch (e) {
		}  	
	}
}

function EP_StoreCount(bInc) {	
	var ndata=0;
	if (EP_BRWHTTP) {
		try {
			var storage = window.localStorage;
		}
		catch (e) {
		}  	
		try {
			ndata = String(storage.getItem("F_CNT" + EP_DC_FormID));	
			if (bInc) {
				if (isNaN(ndata)) ndata=1; else ndata++; 
				storage.setItem("F_CNT" + EP_DC_FormID, ndata);
			} else if (isNaN(ndata)) ndata=0;
		}
		catch (e) {
		}
	}	
	return ndata;		
}

function GetStoSlt() {

	try {
		var storage = window.localStorage;
	}
	catch (e) {
	}  	
	var maxdta=4096;var iRet=-1;var iP=0;
	while (iP<=parseInt(EPSTCNT)) {
		iP++;				
		if (iP>maxdta) break;
		var data1 = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "@@DSFLAG"));	
		if (String(data1)!='1') {
			iRet=iP;break;
		}
	}
	return iRet;
}

function GetSynSlt(iP) {
	try {
		var storage = window.localStorage;
	}
	catch (e) {
	}  	
	var maxdta=4096;var iRet=-1;
	while (iP<=maxdta) {		
		var data1 = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "@@DSFLAG"));	
		if (String(data1)=="1") {
			iRet=iP; break;
		}
		iP++;
	}
	
	return iRet;
}


function EP_SaveToStore(bAlert) {
	var bOK=true;var bExt=false;var tEPSTCNT=0;	preSubSign();
	
	if (EP_BRWHTTP) {
		try {
			var storage = window.localStorage;
		}
		catch (e) {
			alert(cMsgNaReader);
		}  	

		document.HtmlPlusForms["@FORMHEADER"].value = GetDynSubject(EP_DC_HEADER);  
		document.HtmlPlusForms["@FORMLASTMOD"].value = ISODateString();
	
		var ndata = -1;	
		if (pFrmCnt>-1) {ndata = pFrmCnt; bExt=true;}  // data pointer
		else { 
			ndata = GetStoSlt(); 			
	
			if (ndata==-1) ndata=EP_StoreCount(true); 						
			else tEPSTCNT=parseInt(EPSTCNT)+1;			
			
			pFrmCnt = ndata;  
		} 
				
		if (!isNaN(ndata)) {
			storage.setItem("F" + ndata + "_" + EP_DC_FormID + "@@DSFLAG", "1");
			for (var i = 0; i < HtmlFormFields.length; i++) {
				try {					
					var fdata = String(EFormGetValue(HtmlFormFields[i].name));
					storage.setItem("F" + ndata + "_" + EP_DC_FormID + "_" + HtmlFormFields[i].name, String(fdata));
				}
				catch (e) {
					bOK=false; if (!bExt) RemoveDataStore(ndata, false);
					alert(cMsgSaveErr + "\n\n" + e);
				}
			}
			
			if (bOK) {
				if (tEPSTCNT>EPSTCNT) EPSTCNT=tEPSTCNT;
				EP_SetStoreCnt(EPSTCNT); $('#EFS__HttpSubmit').html(oriEFSSubmit + ' <small>(' + EPSTCNT + ')</small>');				
				if (bAlert) jAlert (cMsgSaveOK);				
				//EP_resetE();EP_SaveForLater(false); 
				
			}			
			
		}	
	}
	else alert(cMsgSaveNotPos);	
}

function EP_SaveForLater(bAlert) {
	var bOK=true;
	if (EP_BRWHTTP) {
  	try {
  		var storage = window.localStorage;
  	}
  	catch (e) {
		alert(cMsgNaReader);
  	}  	
	document.HtmlPlusForms["@FORMHEADER"].value = GetDynSubject(EP_DC_HEADER);  
	document.HtmlPlusForms["@FORMLASTMOD"].value = ISODateString();
	
	for (var i = 0; i < HtmlFormFields.length; i++) {
		try {
			var fdata = String(EFormGetValue(HtmlFormFields[i].name)); var data = String(storage.getItem("F" + EP_DC_FormID + "_" + HtmlFormFields[i].name));	
			if (fdata!=data) storage.setItem("F" + EP_DC_FormID + "_" + HtmlFormFields[i].name, String(fdata));
		}
		catch (e) {
			bOK=false; alert(cMsgSaveErr + "\n\n" + e);					
		}				
	}
	if (bAlert&&bOK) jAlert (cMsgSaveOK);
	}
	else if (bAlert) jAlert(cMsgSaveNotPos);	
}

function EP_StoreDlg() {
	var sT=""; var sPT=""; var sL=""; var sV="";
	if (EP_BRWHTTP) {	
		try {
			var storage = window.localStorage;
		}
		catch (e) {
			alert(cMsgNaReader);
		}  		
			// load img
			if (EPSTCNT>=1) EFormOpenDialog("<img src='\" + EP0IMG + \"/wait.gif'>",cTblTtl,1,3,"","",$(window).width()-11,$(window).height()-11,false);					
			//("F" + EP_DC_FormID + "_@FORMHEADER");
			var maxdta=4096; var iT=0; var iP=0;			
			sT+="<input type=text id='fsearch' style='width:100%; font: 10pt Arial;color:#000000;text-decoration:none;' placeholder='" + cTblSrc + "' title='" + cTblSrc + "' x-webkit-speech spellcheck='false'></p>"
			sPT+="$( '#fsearch').autocomplete({ select: function (a, b) { pFrmCnt = b.item.value; EP_RestoreFromStoreExt(b.item.value); $(\"#dialog-confirm\").dialog(\"close\"); }, source: [";
			sT+="<table id='sortable' role='presentation'><thead><tr><th></th><th></th><th class='asc' title='" + cTblTS + "'>" + cTblTS + "</th>";
			for (var i = 0; i < HtmlFormFields.length; i++) {		
				if (HtmlFormFields[i].name.substring(0, 1) != '@' && HtmlFormFields[i].type!='button') {
					var sName=String(HtmlFormFields[i].name);
					if (HtmlFormFields[i].subtype=='mc') sName = sName.substring(0,sName.length-2);			
					var sDesc=String(HtmlFormFields[i].title); if (sDesc=='undefined') sDesc=sName;
					sT+="<th title='" + sDesc + "'>" + sName + "</th>";
				}
			}			
			sT+="</tr></thead><tbody>";			
			
			while (iT<parseInt(EPSTCNT)) {
				iP++;				
				if (iP>maxdta) break;				
				var data1 = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "@@DSFLAG"));	
				if (String(data1)=='1') {
					iT++;sL="";sV=iP;
					
					sT+="<tr><td><a href='#' onClick=' pFrmCnt = " + iP + "; EP_RestoreFromStoreExt(" + iP + "); $(\"#dialog-confirm\").dialog(\"close\"); '>" + cTblEdit + "</a></td>";				
					sT+="<td><a href='#' onClick=' pFrmCnt = " + iP + "; RemoveDataStore(" + iP + "); UptEFCNT(); $(\"#dialog-confirm\").dialog(\"close\"); if (EPSTCNT>0) EP_StoreDlg(); '>" + cTblDel + "</a></td>";

					var tdata = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "_@FORMLASTMOD"));					
					sT+="<td>" + tdata + "</td>";									
					for (var i = 0; i < HtmlFormFields.length; i++) {		
						try {
							if (HtmlFormFields[i].name.substring(0, 1) != '@' && HtmlFormFields[i].type!='button') {
								var data = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "_" + HtmlFormFields[i].name));									
									if (data!=null&&data!='null') {							
										if (HtmlFormFields[i].type!='hidden') {
											sT+="<td>" + String(data) + "</td>";
                                            sL+=String(data + " ");
											
										}
										else if (HtmlFormFields[i].name.substring(0, 4) == 'PCX_' && HtmlFormFields[i].type == 'hidden') {	
											sT+="<td><div style='max-width:100px;max-height:100px;' > <img style='max-height:100px; max-width:100%; margin-left: auto; margin-right: auto;' src='" + String(data) + "'> </div> </td>";
										}
										else {
											sT+="<td></td>";
										}
									}
									else {
										sT+="<td></td>";
									}
							}	
						}										
						catch (e) {}						
					}	
					sT+="</tr>";					
					sPT+="{ label: '" + sL + "', value: '" + sV + "'},"							
				}
			}			
			sT+="</tbody></table>";	
			if (sPT.length>1) sPT=sPT.substr(0, sPT.length-1);						
			sPT+="]});" 
			
			$('#dialog-confirm').dialog('close');
			if (EPSTCNT>=1) EFormOpenDialog(sT,cTblTtl,1,3," sortTable($('table#sortable')); " + sPT,"",$(window).width()-11,$(window).height()-11,false);	// ,800,640			
		}
	else jAlert(cMsgSaveNotPos);			
}

function EP_RestoreFromStoreExt(iP,bM) {  
	if (EP_BRWHTTP) {
  	try {
  		var storage = window.localStorage;
  	}
  	catch (e) {
		alert(cMsgNaReader);
  	}
	for (var i = 0; i < HtmlFormFields.length; i++) {		
		try {
			var data = String(storage.getItem("F" + iP + "_" + EP_DC_FormID + "_" + HtmlFormFields[i].name));			
				if (data!=null&&data!='null') { 
					EFormSetValue(HtmlFormFields[i].name,String(data));				
				}
				if (HtmlFormFields[i].name.substring(0, 6) == '@CVS__') {
					HtmlFormFields[i-2]['obj'].clearCanvas();HtmlFormFields[i-2]['obj'].regenerate(data);			
				}
				if (HtmlFormFields[i].name.substring(0, 4) == 'PCX_' && HtmlFormFields[i].type == 'hidden') {					
					var img = document.getElementById('img_' + HtmlFormFields[i].id.substring(4));
					img.src = data; img.style.display = "block";
				}				
		}
		catch (e) {
		}
		}	
		
		EP_HL_REQ();
		
	}
	else if (bM) jAlert(cMsgSaveNotPos);
}

function EP_RestoreFromStore(bM) {  
	if (EP_BRWHTTP) {
  	try {
  		var storage = window.localStorage;
  	}
  	catch (e) {
		alert(cMsgNaReader);
  	}
	for (var i = 0; i < HtmlFormFields.length; i++) {		
		try {
			var data = storage.getItem("F" + EP_DC_FormID + "_" + HtmlFormFields[i].name);	
				if (data!=null&&data!='null') EFormSetValue(HtmlFormFields[i].name,String(data));				
				if (HtmlFormFields[i].name.substring(0, 6) == '@CVS__') {
					HtmlFormFields[i-2]['obj'].clearCanvas();HtmlFormFields[i-2]['obj'].regenerate(data);			
				}
				if (HtmlFormFields[i].name.substring(0, 4) == 'PCX_' && HtmlFormFields[i].type == 'hidden') {					
					var img = document.getElementById('img_' + HtmlFormFields[i].id.substring(4));
					img.src = data; img.style.display = "block";
				}				
		}
		catch (e) {
		}
		}	
	
		EP_HL_REQ();

	}
	else if (bM) jAlert(cMsgSaveNotPos);
}

function EP_ResetStore() {
	if (EP_BRWHTTP) {
    	try {
    		var storage = window.localStorage;
    	}
    	catch (e) {
		alert(cMsgNaReader);
  	}  	
	for (var i = 0; i < HtmlFormFields.length; i++) {
		var data = String(storage.getItem("F" + EP_DC_FormID + "_" + HtmlFormFields[i].name));	
		try {
			if (data!="") storage.setItem("F" + EP_DC_FormID + "_" + HtmlFormFields[i].name, "");			
		}
		catch (e) {
		}		
	  }	
	}
}

function HtmlCurField() {
  return EFormCurField;
}

function HtmlSetValue(sN,sV) {
	EFormSetValue(sN,sV);
}

function HtmlGetValue(sN) {
  return EFormGetValue(sN);
}

function HtmlGetRequired(sN) {
  return EFormGetRequired(sN);
}

function HtmlSetRequired(sN,sSTATE) {
	EFormSetRequired(sN,sSTATE);
}

function HtmlGetReadonly(sN) {
	return EFormGetReadonly(sN);
}

function HtmlSetReadonly(sN,sSTATE) {
	EFormSetReadonly(sN,sSTATE);
}

function HtmlGetField(sN) {
	return EFormGetField(sN);
}
  
// EPEL Base functions
function EP_CalcX(fld,fldcalc) {
	var ev=fldcalc;ev=ReplaceString(ev,'[','EFGVNum(\"');ev=ReplaceString(ev,']','\")'); EFormSetValue(fld,eval(ev));    
}

function EFGVNum(sN) {	
	var rV=0; rV=EFormGetValue(sN); rV=ReplaceString(String(rV),',','.'); if (isNaN(rV)) rV=0; return Number(rV);	
}

function EP_SumX(fld, fldclc1,fldclc2) {
	var fi=0;var fd=0; var sfld=String(fldclc2 + '__ROW_' + fi + '-' + String(fldclc1) + '-' + fi);
	while (EFormGetField(sfld)!=undefined) {		
		fd+=EFGVNum(sfld);fi++; sfld=String(fldclc2)+'__ROW_'+fi+'-'+String(fldclc1)+'-'+fi;
	}
	EFormSetValue(fld,fd);
}
function EP_ColX(fld, fldcalc,fldcol,fldncol) {
		var ev=fldcalc; ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")');
		eval("try { if (ev!=undefined) { var rs = eval(ev); if (rs) EFormGetField(fld).style.color = fldcol; else EFormGetField(fld).style.color = fldncol; } } catch (e) { }");
}

function EP_ColbX(fld, fldcalc,fldcol) {
		var ev=fldcalc; ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")');
		eval("try { if (ev!=undefined) { var rs = eval(ev); if (rs) EFormGetField(fld).style.backgroundcolor = fldcol; } } catch (e) { }");
}

function EP_LockX(fld, fldcalc) {
	var ev=fldcalc; ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")');
	eval("try { if (ev!=undefined) { var rs = eval(ev); var bXR=false; if (rs) bXR=true; EFormSetReadonly(fld,bXR); } } catch (e) { }");
}

function EP_MandX(fld, fldcalc) {
		var ev=fldcalc; ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")');
		eval("try { if (ev!=undefined) { var rs = eval(ev); var bXR=false; if (rs) bXR=true; EFormSetRequired(fld,bXR); } } catch (e) { }");
}

function EP_HideX(fld, fldcalc) {
		var ev=fldcalc; ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")');
		eval("try { if (ev!=undefined) { var rs = eval(ev); var bXR=true; if (rs) bXR=false; EFormSetVisible(fld,bXR); } } catch (e) { }");
}

function EP_ExprX(fld, fldcalc) {
	var ev=fldcalc;	ev=ReplaceString(ev,'[','EFormGetValue(\"');ev=ReplaceString(ev,']','\")'); EFormSetValue(fld,eval(ev));
}

function EP_SetX(fld, fldcalc,fldval) {
	var ev=fldcalc; ev=ReplaceString(ev,'[','GetFieldSubValue(\"');ev=ReplaceString(ev,']','\")');
	eval("try { if (ev!=undefined) { alert (ev); var rs = eval(ev); if (rs) event.value=fldval;} } catch (e) { }");
}

function EP_RegExpX(fld, fldcalc,fMsg) {
	if (EFormGetValue(fld)!="") {
      		var bOK = String(EFormGetValue(fld)).match(fldcalc);
		if (!bOK) { curField=EFormGetField(fld); jAlert (fMsg,'','EP_RegExpX_oA();');  }      			
	}	
}

function EP_RegExpX_oA() {
	$('#dialog-confirm').dialog('close'); EFormSetFocus(curField);
}

function EP_PersistX(fld,fD,fX) {
	if (fX==''||fX==undefined) fX = fld;
	if (fD==''||fD==undefined) fD = fX;
	fD=ReplaceString(fD,'[','');fD=ReplaceString(fD,']','');
	fV=EFormGetValue(fX);if (!bFormHasLoaded&&trim(fV)=='') fV=getProfile(fD,fX);
	setProfile(fD,fV);
}

function EP_SubscribeX(fld,fS,fX) {
	if (fX==''||fX==undefined) fX = fld;
	if (fS==''||fS==undefined) fS = fX;
	fS=ReplaceString(fS,'[','');fS=ReplaceString(fS,']','');
	getProfile(fS,fX);	
}


function getProfile(varProfileField, sFormField) {
	if (EP_BRWHTTP) {
	try {		
		var storage = window.localStorage;
		if (sFormField==''||sFormField==undefined) sFormField = varProfileField;	
		var data = storage.getItem("FGlob_" + varProfileField);	
		if (data!=null&&data!='null') {
      			if (trim(EFormGetValue(sFormField))=="") EFormSetValue(sFormField,String(data));				
    		}	
	}
	catch (e) {
		//jAlert("getProfile: " + e);
	}
	}

	return data;
}

function setProfile(varProfileField, varValue) {
	if (EP_BRWHTTP) {
	
	try
	{		
		var storage = window.localStorage;
		var data = String(storage.getItem("FGlob_" + varProfileField));	
		if (varValue!=data) storage.setItem("FGlob_" + varProfileField, String(varValue));
	}
	catch (e)
	{
		//jAlert("setProfile: " + e);
	}				

	}
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function EP_MakeNumber(x,d,dz) {
  if (!isNumber(x)) return '0';  
  var e = Math.pow(10, d);
  var k = (Math.round(x * e) / e).toString();
  k += (k.indexOf('.') == -1)? '.00' : '00';
  var p = k.indexOf('.'), m = k.indexOf('-.');
  var f = (p == 0 || m == 0)? String('0' + dz) : dz;
  return k.substring(0, p) + f + k.substring(p+1, p+3);   
  return k;
}

function EP_F(f,dez,sig) {	
	var fx = String(EFormGetValue(f)).replace(',','.');	
	if (fx!="") EFormSetValue(f,EP_MakeNumber(fx,dez,'.'));
}

function contains(s1, s2) {
 var bC=false;
 if (String(s1).indexOf(s2)>=0) bC=true;
 return bC;
}

function BuildDataString () {
	var message = "";var intR=0;var fldval="";	
	for (var i = 0; i < HtmlFormFields.length; i++) {					
		if ( String(HtmlFormFields[i].name).indexOf("@CVS__") !=0 && String(HtmlFormFields[i].name).indexOf("@FORMDATA")!=0 ) {			
			//alert(HtmlFormFields[i].id + " = " + EFormGetValue(HtmlFormFields[i].name));			
			fldval=EFormGetValue(HtmlFormFields[i].name);message+=HtmlFormFields[i].name+"|"+fldval+"|";		
		}
	}		
	message=encodeURIComponent(message);
	return message;
}

function showCal(f) {	
    $('#'+f).datepicker('show');
}

function covUI(bM) {
if (bM) {
	$('<div></div>').attr('id', 'EFS__SubCover').css({
		'position': 'absolute','top': 0,'left': 0,'z-index': 10000,'opacity': 0.3,'width':'100%','height':'100%','background-color':'black','cursor':'wait'
	}).html('').appendTo('body');
	$('#EFS__SubCover').height($(document).height());$('#EFS__SubCover').width($(document).width());

} else {$('#EFS__SubCover').remove();}
}


function EP_GetRandomString24() {
	var Systemdatum = new Date()
	var wTime = new Array("","01","02","03","04","05","06","07","08","09");
	var WMonat = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
	var rPre="";var rSuf="";var rMid="";
	var Tag = Systemdatum.getDate();
	var Monat = Systemdatum.getMonth();Monat = WMonat[Monat];
	var Minutes = Systemdatum.getMinutes(); if (Minutes<10) Minutes = wTime[Minutes];
	var Seconds = Systemdatum.getSeconds(); if (Seconds<10) Seconds = wTime[Seconds];
	var Hours = Systemdatum.getHours(); if (Hours<10) Hours = wTime[Hours];
	var Jahr = Systemdatum.getFullYear()
	if (Tag<10) Tag = wTime[Tag];
	for (ix=0;ix<=4;ix++) rPre+=String(Math.floor(Math.random() * 10))
	rMid = String(Tag + Monat + Jahr + Hours + Minutes + Seconds); // 14 stellen
	for (ix=0;ix<=4;ix++) rSuf+=String(Math.floor(Math.random() * 10))
	return (String(rPre + rMid + rSuf));
}

var color = new Object();
color.blue = "#0000FF";color.black = "#000000";color.white = "#FFFFFF";color.red = "#FF0000";
color.green = "#00FF00";color.yellow = "#FFFF00";color.cyan = "#00FFFF";color.dkGray = "#696969";
color.ltGray = "#D3D3D3";color.gray = "#BEBEBE";color.magenta = "#FF0090";color.transparent = "#FFFFFF"; // no real transparency for now

function EPcpys(did,sid) {
	var c=document.getElementById(sid);c.height = $('.'+did).height(); c.width = $('.'+did).width(); 
}

function EP_AfOnL() {
  		for (var fldName in EP_AFD) {
    		  if (EP_AFD[fldName].onl == '1') {
					var varAfKeys = String(EP_AFD[fldName].kfd).split("|");
					for (var iy = 0; iy<varAfKeys.length; iy+=2) {						
						if (EFormGetField(varAfKeys[iy])) {
							EFormSetValue('@LOOKUPDONE','1');
							EP_AF(EFormGetField(varAfKeys[iy]),fldName,1);
						}
					}
		  	  }
		}
}

function EP_AF(EPevent,EPid, EPoL) {
		var xv="";xv=trim(EPevent.value);	
		if (xv!=""&&xv!=undefined) {
			curEPid=EPid;curEPoL=EPoL;curEPevent=EPevent;
			if (EP_AFD[String(curEPid)].qst!=""&&curEPoL!=1) {
				jAlert (EP_AFD[String(curEPid)].qst,'',"EP_AFoA();",1,2);
			}
			else {				
				EP_AFoA(EPevent);		
			}
		}
}

function EP_AFoA(f)
{
			if (f==undefined) f=curEPevent;if (typeof(window.Form_onLookup)!='undefined') Form_onLookup(f);	// prelookupevent			
			
			var varAfKeys = String(EP_AFD[String(curEPid)].kfd).split("|");var tempstr="";
			EFormSetValue('@RESPONSEMSG',EP_AFD[String(curEPid)].fal);EFormSetValue('@RESPONSEERR',EP_AFD[String(curEPid)].fer);			
			for (var iy = 0; iy<varAfKeys.length; iy+=2) { 
				if (EFormGetValue(varAfKeys[iy])!="") { 
					if (iy>0) tempstr+="|"; tempstr+=varAfKeys[iy] + "|" + EFormGetValue(varAfKeys[iy]) + "|" + varAfKeys[iy+1]; 
				} 
			}
			var varLookup= EP_AFD[String(curEPid)].lnk + "||" + EP_AFD[String(curEPid)].tbl + "||" + tempstr + "||" + EP_AFD[String(curEPid)].ffd + "||" + EP_AFD[String(curEPid)].dfd + "||" + EP_DC_LANG;			
			EFormSetValue('@LOOKUP',varLookup);			
			var sData = {};	sData["@LOOKUP"] = varLookup; sData["@RESPONSEMSG"] = EP_AFD[String(curEPid)].fal; sData["@RESPONSEERR"] = EP_AFD[String(curEPid)].fer; sData["@AJAX"] = "1";
			$.ajax({ url: document.getElementById('HPFsubmit').getAttribute("action"), type: "POST", data: sData, 
			success: function(data) {								
				if (String(data).indexOf("// HTMLPLUSGUID") > -1) { eval(data);  if (typeof(window.Form_afterLookup)!='undefined') Form_afterLookup(f);	}
			},			
			statusCode: {
				404: function() {
						jAlert('page not found');
					}		
			},		
			error:  
				function(jqXHR, textStatus, errorThrown) {					
					EFormSetValue('@LOOKUP',"");			
				},
			complete: function() { 
				EFormSetValue('@LOOKUP',"");			
			}
			});						
			
}

function hx2R(h) {return parseInt((tHx(h)).substring(0,2),16)} 
function hx2G(h) {return parseInt((tHx(h)).substring(2,4),16)}
function hx2B(h) {return parseInt((tHx(h)).substring(4,6),16)}
function tHx(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

function delSign(fI) {
	try {
		for (var i = 0; i < HtmlFormFields.length; i++) {
		 if (HtmlFormFields[i].id==fI) { 
			if (HtmlFormFields[i].ink=='1') {
				HtmlFormFields[i]['obj'].clearCanvas();	EFormSetValue(HtmlFormFields[i].name, '');epelall();break;
			}
		 }
		}
	} catch (e) { }
}

function colSign(i,fI,sCol) {
	try {
		var element = document.getElementById(fI); var ctx = element.getContext("2d");
		var width = parseInt(element.getAttribute("width"));var height = parseInt(element.getAttribute("height"));var n=0;
		var imgd = ctx.getImageData(0, 0, width, height);		
		var ir=hx2R(sCol);var ig=hx2G(sCol);var ib=hx2B(sCol);	
		for (var idx = 0, n = imgd.data.length; idx < n; idx += 4) {
			if (imgd.data[idx]==0&&imgd.data[idx+1]==0&&imgd.data[idx+2]==0) { }
			else {
				imgd.data[idx + 0]=ir;imgd.data[idx + 1]=ig;imgd.data[idx + 2]=ib;			
			}	
		}	
	   ctx.putImageData(imgd, 0, 0);	
	   if (document.getElementById('CVS_' + HtmlFormFields[i].id).value.length>0) HtmlFormFields[i]['obj'].regenerate(document.getElementById('CVS_' + HtmlFormFields[i].id).value);          
	}
	catch (e) { }
}


  function abortRead() {
    reader.abort();
  }

  function ImgErrorHandler(evt) {
    switch(evt.target.error.code) {
      case evt.target.error.NOT_FOUND_ERR:
        alert('File Not Found!');
        break;
      case evt.target.error.NOT_READABLE_ERR:
        alert('File is not readable');
        break;
      case evt.target.error.ABORT_ERR:
        break; 
      default:
        alert('An error occurred reading this file.');
    };
  }

  function ImgUpdateProgress(evt) {
    if (evt.lengthComputable) {
      var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
      if (percentLoaded <= 100) {
  		$("#pb"+curImgCtl).show();	
		$("#pb"+curImgCtl).progressbar({ value: percentLoaded }).children('.ui-progressbar-value').html(percentLoaded + '%').css("display", "block");		
      }
    }
  }

function setImg(sId,file) {
	try {
	
		if (typeof FileReader !== "undefined") {
		
			if (file.type.match('image.*')) {					
				if (document.getElementById('img_' + sId)) {							
					var img = document.getElementById('img_' + sId);img.file = file;				
					curImgCtl=sId; var reader = new FileReader();
					reader.onerror = ImgErrorHandler;
					reader.onprogress = ImgUpdateProgress;
					reader.onabort = function(e) { alert('File read cancelled'); };
					
					reader.onload = (function(aImg) { return function(e) { 
						aImg.src = e.target.result; aImg.style.display = "block"; for (var i = 0; i < HtmlFormFields.length; i++) { if (HtmlFormFields[i].id == 'PCX_' + sId) { EFormSetValue(HtmlFormFields[i].name, e.target.result);
						$("#pb"+sId).progressbar({ value: 100 }).children('.ui-progressbar-value').html('100%').css("display", "block");				
						if (typeof(window.Form_afterFileLoad)!='undefined') Form_afterFileLoad(document.getElementById(sId));
						setTimeout("$('#pb" +sId +"').hide();", 2000);
						break; }}};		
					})(img);		
					reader.readAsDataURL(file);
				}
			}
			epelall();
		} else alert(cMsgNaReader);
	}
	catch (e) {				
		alert(cMsgNaReader);
	}
}


function doImgDrop(event,sId) {

	try {
		var file = event.dataTransfer.files[0];
		setImg(sId,file);
  
	}
	catch (e) {				
	}
  
}

function pDE(event) {
	event.stopPropagation(); event.preventDefault();
}

function EPCHKTPL(f,tpl) {
  var fValue = String(f.value); var bChk=true; var vIsChr=0;var cX=""; var cP=""; var fxValue="";
  if (fValue.length>0) {
		curField=f;
		for (var i=0;i<fValue.length;i++) {
			cX=fValue.charAt(i);cP=tpl.charAt(i);
			if (cP=='A') {
				vIsChr=cX.search(/\D/);	if (vIsChr<0) bChk=false; 
				fxValue+=cX;
			}
			else if (cP=='N') {
				vIsChr=cX.search(/\d/); if (vIsChr<0) bChk=false; 
				fxValue+=cX;
			}
			else if (cP=='X') {
				vIsChr=cX.search(/\d/); if (vIsChr<0) vIsChr=cX.search(/\D/);
				if (vIsChr<0) bChk=false; 
				fxValue+=cX;
			}
			else {
				fxValue+=cP;
			}
		}         
	}	

	if (!bChk) {
		jAlert (cMsgInvTemplate + "\n\n(" + tpl + ")",'','EP_VAL_oA();');
	}
	else f.value = String(fxValue);
	return bChk;
}

function ISODateString(d){
 if (d==undefined) d=new Date();
 function pad(n){return n<10 ? '0'+n : n}
 return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+' '
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds());
}

function timestamp(d) {
 if (d==undefined) d=new Date();
 function pad(n){return n<10 ? '0'+n : n}
 return String(d.getFullYear()) + String(pad(d.getMonth()+1)) + String(pad(d.getDate())) + String(pad(d.getHours())) + String(pad(d.getMinutes())) + String(pad(d.getSeconds())) + String(pad(d.getMilliseconds()));
}

function timestampstr(d) {
 if (d==undefined) d=new Date();
 function pad(n){return n<10 ? '0'+n : n}
 return String(d.getFullYear()) + '-' + String(pad(d.getMonth()+1)) + '-' + String(pad(d.getDate())) + ' ' + String(pad(d.getHours())) + ':' + String(pad(d.getMinutes())) + ':' + String(pad(d.getSeconds())) + ':' + String(pad(d.getMilliseconds()));
}


function EPKEYP(ev) {
  if (!bFieldEnter) {
    if (!ev) ev = window.event;
    if (ev.keyCode==37||ev.keyCode==33) gotoP(-cPagingY);
    if (ev.keyCode==39||ev.keyCode==34) gotoN(cPagingY);
  }
}
document.onkeydown = EPKEYP;


var sortTable = function(obj) {
	if(!obj.length) return;
	var Helper = {
		replaceSpecials: function(str) {
			var specials = {"ö":"oe","ä":"ae","ü":"ue","ß":"ss"};
			for (var char in specials) {
				var regExp = new RegExp(char,"g");str = str.replace(regExp,specials[char]);
			}
			return str;
		}
	}	
	obj.each(function() {
		$('tbody tr:even', obj).addClass("even");
		var th = $('th', obj);
		th.each(function(index) {
			if (!$(this).hasClass("none")) {
				var asc = false;
				$(this).click(function() {
					asc ? asc = false : asc = true;
					th.removeClass("desc asc");	asc?$(this).addClass("asc"):$(this).addClass("desc");
					var tableRows = $('tbody > tr',obj).get(); var isNumeric = $(this).hasClass("numtab");
					tableRows.sort(function(a, b) {
						var sortA = Helper.replaceSpecials($(a).children('td').eq(index).text().toLowerCase()); var sortB = Helper.replaceSpecials($(b).children('td').eq(index).text().toLowerCase());
						var num; asc ? num = 1 :num = -1;
						if (isNumeric) return asc ? sortA - sortB : sortB - sortA;
						return (sortA == sortB) ? 0 : (sortA > sortB) ? num : num * -1;
					});				
					for (var tr in tableRows) {
						$('tbody',obj).append(tableRows[tr]);
					}
					$('tbody tr', obj).removeClass("even");	$('tbody tr:even', obj).addClass("even");				
				});
			}
		});
	});
	
	$('th.asc').trigger('click');$('th.asc').trigger('click');
}


var triggerElementID = null;  var fingerCount = 0;var startX = 0;var startY = 0;var curX = 0;var curY = 0;var deltaX = 0;var deltaY = 0;var horzDiff = 0;var vertDiff = 0; var minLength = 420;  var swipeLength = 0;var swipeAngle = null;var swipeDirection = null;
function touchStart(event,passedName) {
	fingerCount = event.touches.length;
	if ( fingerCount == 1 ) {
		startX = event.touches[0].pageX;startY = event.touches[0].pageY;triggerElementID = passedName;
	} else {
		touchCancel(event);
	}
}

function touchMove(event) {
	if ( event.touches.length == 1 ) {
		curX = event.touches[0].pageX;curY = event.touches[0].pageY;
	} else {
		touchCancel(event);
	}
}

function touchEnd(event) {
	if ( fingerCount == 1 && curX != 0 ) {
		swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
		if ( swipeLength >= minLength ) {
			caluculateAngle();determineSwipeDirection();processingRoutine();touchCancel(event); 
		} else {
			touchCancel(event);
		}	
	} else {
		touchCancel(event);
	}
}

function touchCancel(event) {
	fingerCount = 0;startX = 0;startY = 0;curX = 0;curY = 0;deltaX = 0;deltaY = 0;horzDiff = 0;vertDiff = 0;swipeLength = 0;swipeAngle = null;swipeDirection = null;triggerElementID = null;
}

function caluculateAngle() {
	var X = startX-curX;var Y = curY-startY;var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2)));
	var r = Math.atan2(Y,X); swipeAngle = Math.round(r*180/Math.PI); 
	if ( swipeAngle < 0 ) { swipeAngle =  360 - Math.abs(swipeAngle); }
}

function determineSwipeDirection() {
	if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
		swipeDirection = 'left';
	} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
		swipeDirection = 'left';
	} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
		swipeDirection = 'right';
	} else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
		swipeDirection = 'down';
	} else {
		swipeDirection = 'up';
	}
}

function processingRoutine() {
	var swipedElement = document.getElementById(triggerElementID);
	if ( swipeDirection == 'left' ) {
		gotoN();
	} else if ( swipeDirection == 'right' ) {
		gotoP();
	} else if ( swipeDirection == 'up' ) {
		gotoL();
	} else if ( swipeDirection == 'down' ) {
		gotoF();
	}
}

var Compress = (function (canvas) {
 function Compress(img, onCompress) {
  var load = typeof img == "string", i = load || img;
   if (load) { i = new Image; i.onload = onload;i.onerror = onerror; }
   i._onCompress = onCompress; load ? (i.src = img) : onload.call(img);
 } 
 function onerror() { throw ("not found: " + this.src); }
 function onload() {
   var img = this,onCompress = img._onCompress;   
   delete img._onCompress;
   canvas.width = img.width;canvas.height = img.height;
   context.drawImage(img,0,0,img.width,img.height,0,0,img.width,img.height);  
   onCompress(canvas.toDataURL("image/jpeg", 0.3));  
 }
 var context = canvas.getContext("2d"),round = Math.round; 
 return Compress; 
} (this.document.createElement("canvas")) ); 

